package com.grj.template.boot.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;


/**
 * @author: eren
 * @date: 2023-03-05 12:29
 * @description:
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class MybatisPlusConfig implements MetaObjectHandler {

    private final HttpServletRequest httpServletRequest;
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }

    @Bean
    public PaginationInnerInterceptor paginationInnerInterceptor(){
        return new PaginationInnerInterceptor();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
//        log.info("公共字段自动填充: "+BaseContext.getCurrentId());
        this.setFieldValByName("status", "1", metaObject);
        this.setFieldValByName("createTime", Calendar.getInstance().getTime(), metaObject);
        this.setFieldValByName("updateTime", Calendar.getInstance().getTime(), metaObject);
        this.setFieldValByName("createUser", Long.valueOf(httpServletRequest.getAttribute("id").toString()), metaObject);
        this.setFieldValByName("updateUser", Long.valueOf(httpServletRequest.getAttribute("id").toString()), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", Calendar.getInstance().getTime(), metaObject);
        this.setFieldValByName("updateUser", Long.valueOf(httpServletRequest.getAttribute("id").toString()), metaObject);
    }
}
